<template>
  <div class="home-container">
    <!-- 顶部背景和标题 -->
    <div class="home-header">
      <div class="header-content">
        <img
          src="@/assets/homeOther/home_top_logo.png"
          alt="logo"
          class="header-logo"
          @click="openLogoutConfirm"
        />
        <div class="title-row">
          <div class="title">北京君初律师事务所</div>
          <img
            :src="messageIconSrc"
            alt="消息"
            class="message-icon"
            @click="goToMessage"
          />
        </div>
        <div class="subtitle">工作台</div>
      </div>
    </div>

    <!-- 功能模块 -->
    <div class="function-modules">
      <div class="module-item" @click="goToModule('organization')">
        <img src="@/assets/homeOther/organizational_icon.png" alt="组织架构" />
        <span>组织架构</span>
      </div>
      <div class="module-item" @click="goToModule('contract')">
        <img src="@/assets/homeOther/contract_icon.png" alt="合同" />
        <span>合同</span>
      </div>
      <!-- <div class="module-item" @click="goToModule('detail')">
        <img src="@/assets/homeOther/country_page_icon.png" alt="详情" />
        <span>详情</span>
      </div> -->
      <!-- 报销 -->
      <div class="module-item" @click="goToModule('report')">
        <img src="@/assets/homeOther/reimburse_icon.png" alt="报销" />
        <span>报销</span>
      </div>
      <div class="module-item" @click="goToModule('pay')">
        <img src="@/assets/homeOther/pay_icon.png" alt="付款" />
        <span>付款</span>
      </div>
      <!-- 管理员展示：仅管理员可见 -->
        <div class="module-item" v-if="isAdmin" @click="goToModule('message')">
        <img src="@/assets/homeOther/home_message.png" alt="公告" />
        <span>公告</span>
      </div>
    </div>

    <!-- OA审批统计 -->
    <div class="oa-section">
      <!-- 加载骨架屏 -->
      <div v-if="loading" class="oa-skeleton">
        <van-skeleton :row="6" :loading="true" />
      </div>
      
      <!-- 实际内容 -->
      <div v-else>
        <div class="section-header" @click="goToApprovals()">
          <div class="section-title">
            <img
              src="@/assets/homeOther/examine_icon.png"
              alt="OA"
              class="oa-icon"
            />
            <span>OA审批</span>
        </div>
           <van-icon name="arrow" class="arrow-icon" />
         </div>
      </div>

      <div class="statistics-grid" v-if="!loading">
        <div class="stat-item pending" @click="goToApprovals(0)">
          <div class="stat-number">{{ statistics.pending }}</div>
          <div class="stat-label">待处理</div>
          <img
            src="@/assets/homeOther/pending _processing_bg.png"
            alt="待处理"
            class="stat-bg-icon"
          />
        </div>
        <div class="stat-item processed" @click="goToApprovals(1)">
          <div class="stat-number">{{ statistics.processed }}</div>
          <div class="stat-label">已处理</div>
          <img
            src="@/assets/homeOther/processed_bg.png"
            alt="已处理"
            class="stat-bg-icon"
          />
        </div>
        <div class="stat-item initiated" @click="goToApprovals(2)">
          <div class="stat-number">{{ statistics.initiated }}</div>
          <div class="stat-label">已发起</div>
          <img
            src="@/assets/homeOther/initiated_bg.png"
            alt="已发起"
            class="stat-bg-icon"
          />
        </div>
        <div class="stat-item other" @click="goToApprovals(3)">
          <div class="stat-number">{{ statistics.other }}</div>
          <div class="stat-label">我收到的</div>
          <img
            src="@/assets/homeOther/receive_bg.png"
            alt="我收到的"
            class="stat-bg-icon"
          />
        </div>
      </div>

      <!-- 加载状态 -->
      <div class="loading-wrapper" v-if="loading">
        <van-loading size="24px" color="#1989fa">加载中...</van-loading>
      </div>
    </div>

    <!-- 待办事项 -->
    <div class="todo-section">
      <div class="section-header">
        <div class="section-title" @click="goToApprovals(0)">
          <img
            src="@/assets/homeOther/handle_icon.png"
            alt="待办"
            class="todo-icon"
          />
          <span>待办</span>
        </div>
        <van-badge
          :content="statistics.pending"
          max="10"
          v-if="statistics.pending > 0"
        />
        <van-icon name="arrow" class="arrow-icon" />
      </div>

      <!-- 有待办数据时显示最新的一条 -->
      <div v-if="latestTodo" class="todo-list">
        <div class="todo-item" @click="latestTodo && handleTodoClick(latestTodo)">
          <div class="todo-content">
            <!-- <div class="todo-header">
              <span class="todo-type">{{ latestTodo.todoType }}</span>
              <span class="todo-id" v-if="latestTodo.no">#{{ latestTodo.no }}</span>
            </div> -->
            <div class="todo-title">{{ getApprovalTitle(latestTodo) }}</div>
            <div class="todo-details">
              <!-- 合同类型待办 -->
              <template v-if="latestTodo.type === '1'">
                <div class="detail-item" v-if="latestTodo.name">
                  <span class="label">合同名称：</span>
                  <span class="value">{{ latestTodo.name }}</span>
                </div>
                <div class="detail-item" v-if="latestTodo.contractTermType">
                  <span class="label">合同期限：</span>
                  <span class="value">{{
                    getTermTypeName(latestTodo.contractTermType)
                  }}</span>
                </div>
                <div class="detail-item" v-if="latestTodo.ourEntityName">
                  <span class="label">我方主体：</span>
                  <span class="value">{{ latestTodo.ourEntityName }}</span>
                </div>
                <div class="detail-item" v-if="latestTodo.otherEntityName">
                  <span class="label">对方主体：</span>
                  <span class="value">{{ latestTodo.otherEntityName }}</span>
                </div>
              </template>

              <!-- 报销类型待办 -->
              <template v-else-if="latestTodo.type === '2'">
                <div class="detail-item" v-if="latestTodo.amount">
                  <span class="label">报销金额：</span>
                  <span class="value ">{{ latestTodo.amount }}</span>
                </div>
                <div v-if="latestTodo.amountDate" class="detail-item">
                  <span class="label">费用发生日期：</span>
                  <span class="value">
                    {{ formatDate(latestTodo.amountDate) }}</span
                  >
                </div>

                <div class="detail-item" v-if="latestTodo.amountType">
                  <span class="label">报销类型：</span>
                  <span class="value">{{
                    getExpenseTypeName(latestTodo.amountType)
                  }}</span>
                </div>
                <div class="detail-item" v-if="latestTodo.amountRemark">
                  <span class="label">报销明细：</span>
                  <span class="value">{{ latestTodo.amountRemark }}</span>
                </div>
              </template>

              <!-- 付款类型待办 -->
              <template v-else-if="latestTodo.type === '3'">
                <div class="detail-item" v-if="latestTodo.payAmount">
                  <span class="label">付款金额：</span>
                  <span class="value">{{ latestTodo.payAmount }}</span>
                </div>
                <div v-if="latestTodo.payDate" class="detail-item">
                  <span class="label">付款日期：</span>
                  <span class="value ">{{
                    formatDate(latestTodo.payDate)
                  }}</span>
                </div>
                <div v-if="latestTodo.payObjectName" class="detail-item">
                  <span class="label">付款对象：</span>
                  <span class="value ">{{ latestTodo.payObjectName }}</span>
                </div>
                <div class="detail-item" v-if="latestTodo.payRemark">
                  <span class="label">付款说明：</span>
                  <span class="value">{{ latestTodo.payRemark }}</span>
                </div>
              </template>
            </div>

            <!-- 通用信息 -->
            <!-- <div class="todo-meta">
              <div class="meta-item">
                <span class="label">部门：</span>
                <span class="value">{{ latestTodo.department }}</span>
              </div>
              <div class="meta-item" v-if="latestTodo.createDate">
                <span class="label">创建时间：</span>
                <span class="value">{{ formatDate(latestTodo.createDate) }}</span>
              </div>
            </div> -->
          </div>
          <div class="todo-actions">
            <van-button
              size="small"
              class="reject-btn"
              :loading="dealLoading"
              :disabled="dealLoading"
              @click.stop="latestTodo && handleReject(latestTodo)"
            >
              拒绝
            </van-button>
            <van-button
              size="small"
              type="primary"
              class="approve-btn"
              :loading="dealLoading"
              :disabled="dealLoading"
              @click.stop="latestTodo && handleApprove(latestTodo)"
            >
              同意
            </van-button>
          </div>
        </div>
      </div>

      <!-- 无待办数据时显示空状态 -->
      <div v-else class="empty-state">
        <div class="empty-icon">
          <img src="@/assets/homeOther/handle_bg.png" alt="无待办" />
        </div>
        <div class="empty-text">真棒，待办都处理完啦！</div>
      </div>
    </div>

    <!-- AI助手按钮 -->
    <div class="ai-assistant">
      <div class="ai-button" @click="openAI">
        <img src="@/assets/homeOther/ai_icon.png" alt="AI" />
      </div>
    </div>

    <!-- 退出登录二次确认弹窗 -->
    <van-dialog
      v-model:show="showLogoutConfirm"
      title="确认退出"
      :message="logoutMessage"
      show-cancel-button
      confirm-button-text="退出登录"
      cancel-button-text="取消"
      @confirm="onConfirmLogout"
    />
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, computed } from "vue";
import { useRouter } from "vue-router";
import {
  getExpenseTypeName,
  getAmountTypeName,
  getTermTypeName,
} from "@/utils/enums";
import { formatDateUTC as formatDate } from '@/utils/formatters'
import { showToast } from "vant";
import { getUserById } from "@/api/user";
import { storage } from "@/utils/storage";
import {
  queryPendingApi,
  queryProcessedApi,
  queryInitiatedApi,
  queryReceivedApi,
  dealContractApi,
  dealBaoXiaoApi,
  dealPayApi,
  queryDetailApi,
  queryMessageApi,
} from "@/api/home";

// 顶部消息图标：根据未读数量动态切换
import messageIcon from '@/assets/homeOther/message_icon.png';
import noMessageIcon from '@/assets/homeOther/no_message.png';

// 路由实例
const router = useRouter();

// 加载状态 - 初始为false，避免闪烁
const loading = ref(false);
// 审核操作加载状态（独立于页面初始加载）
const dealLoading = ref(false);

// 统计数据
const statistics = reactive({
  pending: 0,
  processed: 0,
  initiated: 0,
  other: 0,
});

// 当前登录用户信息与管理员判断（与部门页面保持一致逻辑）
const currentUser = ref<any>(null);
const currentUserDetail = ref<any>(null);
const isAdmin = computed(() => {
  return currentUserDetail.value?.admin === 1;
});

// 未读消息数量，用于切换消息图标
const unreadCount = ref(0);
// 计算图标地址：有未读则显示“消息”图标，无未读显示“无消息”图标
const messageIconSrc = computed(() => {
  return unreadCount.value > 0 ? messageIcon : noMessageIcon;
});

// 退出登录确认弹窗状态与文案
const showLogoutConfirm = ref(false);
const currentUserName = computed(() => {
  const detail = currentUserDetail.value || {};
  const basic = currentUser.value || storage.getUserInfo() || {};
  return (
    detail.name || detail.userName || basic.name || basic.userName || '未知用户'
  );
});
const logoutMessage = computed(
  () => `当前登录人：${currentUserName.value}，确认退出？`
);

const openLogoutConfirm = () => {
  showLogoutConfirm.value = true;
};

// 清理cookie（仅对非 HttpOnly 有效）
const clearCookie = (name: string) => {
  try {
    document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/`;
  } catch (e) {
    console.warn('清理cookie失败:', name, e);
  }
};

const performLogoutCleanup = () => {
  try {
    // 封装的登出清理（按用户/会话前缀）
    storage.logout();
    // 兜底：清除全部存储
    localStorage.clear();
    sessionStorage.clear();
    // 尝试清理常见token cookie（非HttpOnly时有效）
    ['refreshToken', 'token', 'accessToken'].forEach(clearCookie);
  } catch (e) {
    console.error('退出清理过程出现异常:', e);
  }
};

const onConfirmLogout = () => {
  showLogoutConfirm.value = false;
  performLogoutCleanup();
  // 跳转到登录页
  try {
    router.replace({ path: '/login' });
  } catch (e) {
    window.location.href = '#/login';
  }
};

// 获取当前登录用户信息（参考部门页面实现）
const getCurrentUserInfo = async () => {
  try {
    const userInfo = storage.getUserInfo();
    if (userInfo) {
      currentUser.value = userInfo;
      const response = await getUserById(userInfo.id?.toString() || userInfo.userId?.toString());
      if (response.code === 0) {
        currentUserDetail.value = response.data;
        console.log("是否为管理员:", response.data.admin === 1);
      }
    }
  } catch (error) {
    console.error("获取用户信息失败:", error);
  }
};

// 获取OA审批统计数据
const getOAStatistics = async (showLoading = true) => {
  if (showLoading) {
    loading.value = true;
  }
  try {
    // 并发请求所有统计数据
    const [pendingRes, processedRes, initiatedRes, receivedRes] =
      await Promise.all([
        queryPendingApi(),
        queryProcessedApi(),
        queryInitiatedApi(),
        queryReceivedApi(),
      ]);

    // 更新统计数据
    if (pendingRes.code === 0) {
      statistics.pending = pendingRes.data.pendingTotal || 0;

      // 处理待办数据 - 从resultList中获取第一条数据
      const { data } = pendingRes;
      let firstTodo = null;

      if (data.resultList && data.resultList.length > 0) {
        const item = data.resultList[0];

        // 根据type字段确定待办类型
        let todoType = "未知";
        switch (item.type) {
          case "1":
            todoType = "合同";
            break;
          case "2":
            todoType = "报销";
            break;
          case "3":
            todoType = "付款";
            break;
        }

        // 直接使用接口字段，添加类型标识
        firstTodo = {
          ...item,
          todoType, // 使用todoType避免与原type字段冲突
        };
      }

      // 更新待办列表
      todoList.value = firstTodo ? [firstTodo] : [];
    }

    if (processedRes.code === 0) {
      statistics.processed = processedRes.data.processedTotal || 0;
    }
    if (initiatedRes.code === 0) {
      statistics.initiated = initiatedRes.data.initiatedTotal || 0;
    }
    if (receivedRes.code === 0) {
      statistics.other = receivedRes.data.receivedTotal || 0;
    }
  } catch (error) {
    console.error("获取OA统计数据失败:", error);
    if (showLoading) {
      showToast("获取统计数据失败");
    }
  } finally {
    if (showLoading) {
      loading.value = false;
    }
  }
};

// 获取消息未读数量（用于顶部消息图标切换）
const fetchUnreadStatus = async () => {
  try {
    const userInfo = storage.getUserInfo();
    const id = userInfo?.id?.toString() || userInfo?.userId?.toString();
    if (!id) return;
    const res = await queryMessageApi(id);
    if (res && res.code === 0 && res.data) {
      unreadCount.value = Number(res.data.totalUnread || 0);
    }
  } catch (error) {
    console.error('获取消息未读数失败:', error);
    // 失败时不影响页面使用，维持默认图标
  }
};

// 待办事项数据类型 - 直接使用接口字段
interface TodoItem {
  id: string;
  name: string;
  createDate: string | null;
  createId: number;
  no?: string | null;
  department: string;

  // 审批相关字段
  firstApprover: number;
  secondApprover: number;
  thirdApprover: number;
  nowApprover: number;
  firstApproverState: number;
  secondApproverState: number;
  thirdApproverState: number;
  approveDate?: string | null;

  // 合同特有字段
  contractTermType?: string | null;
  contractNote?: string | null;
  ourEntityName?: string | null;
  otherEntityName?: string | null;
  ourCharge?: string | null;
  otherCharge?: string | null;
  signingMethod?: string | null;
  signTime?: string | null;
  sealType?: string | null;

  // 报销特有字段
  amount?: number | null;
  amountType?: string | null;
  amountDate?: string | null;
  amountRemark?: string | null;

  // 付款特有字段
  payAmount?: number | null;
  payDate?: string | null;
  payRemark?: string | null;
  payObject?: number | null;
  payObjectName?: number | null; 
  // 类型标识字段
  type: string; // 后端返回的类型：1-合同，2-报销，3-付款
  todoType?: string; // 前端显示的类型：合同/报销/付款
}

// 待办事项列表
const todoList = ref<TodoItem[]>([]);

// 计算属性：获取最新的一条待办事项
const latestTodo = computed(() => {
  if (todoList.value.length === 0) return null;
  // 按创建时间排序，返回最新的一条
  return todoList.value.sort((a, b) => {
    const dateA = a.createDate ? new Date(a.createDate).getTime() : 0;
    const dateB = b.createDate ? new Date(b.createDate).getTime() : 0;
    return dateB - dateA;
  })[0];
});
// 获取审批标题（createName + type组合）
const getApprovalTitle = (item: any) => {
  const createName = item.createName || "未知用户";
  let typeText = "";

  switch (item.type) {
    case "1":
      typeText = "合同审批";
      break;
    case "2":
      typeText = "报销单据";
      break;
    case "3":
      typeText = "付款单据";
      break;
    default:
      typeText = "审批";
  }

  return `${createName}提交的${typeText}`;
};
// 跳转到功能模块
const goToModule = (module: string) => {
  try {
    switch (module) {
      case "organization":
        router.push({
          path: "/organization",
          replace: false
        }).catch(err => {
          console.error('导航失败:', err);
          // 如果导航失败，尝试使用location.href强制跳转
          window.location.href = '#/organization';
        });
        break;
      case "contract":
        router.push({
          path: "/contract/add",
          replace: false
        }).catch(err => {
          console.error('导航失败:', err);
          window.location.href = '#/contract/add';
        });
        break;
      case "report":
        router.push({
          path: "/expense/add",
          replace: false
        }).catch(err => {
          console.error('导航失败:', err);
          window.location.href = '#/expense/add';
        });
        break;
  case "pay":
    router.push({
      path: "/contract/addPay",
      replace: false
    }).catch(err => {
      console.error('导航失败:', err);
      window.location.href = '#/contract/addPay';
    });
    break;
      case "message":
        router.push({
          path: "/message",
          replace: false
        }).catch(err => {
          console.error('导航失败:', err);
          window.location.href = '#/message';
        });
        break;
  default:
    showToast("功能开发中");
    }
  } catch (error) {
    console.error('导航异常:', error);
    // 根据模块名称进行备用导航
    // 使用 Record<string, string> 明确索引签名，避免 TS 对字符串索引报错
    const routes: Record<string, string> = {
      organization: "#/organization",
      contract: "#/contract/add",
      report: "#/expense/add",
      pay: "#/contract/addPay",
      message: "#/message",
    };
    const fallback = routes[module];
    if (fallback) {
      window.location.href = fallback;
    } else {
      // 未知模块兜底提示
      showToast("功能开发中");
    }
  }
};

// 顶部消息入口：跳转到公告/消息页面
const goToMessage = () => {
  // 复用已有模块跳转逻辑，带兜底
  try {
    router.push({
      path: "/message",
      query: { mode: 'notify' },
      replace: false,
    }).catch((err) => {
      console.error("导航失败:", err);
      window.location.href = "#/message";
    });
  } catch (error) {
    console.error("导航异常:", error);
    window.location.href = "#/message";
  }
};


// 处理待办点击
const handleTodoClick = (item: TodoItem) => {
  // 根据类型跳转到对应的详情页面
  switch (item.type) {
    case "1": // 合同
      router.push({
        path: `/contract/detail/${item.id}`,
        query: {
          type: item.type,
          from: 'home'
        },
      });
      break;
    case "2": // 报销
      router.push({
        path: `/expense/detail/${item.id}`,
        query: {
          type: item.type,
          from: 'home'
        },
      });
      break;
    case "3": // 付款
      router.push({
        path: `/contract/detail/pay-detail/${item.id}`,
        query: {
          type: item.type,
          from: 'home'
        },
      });
      break;
    default:
      showToast("未知的待办类型");
  }
};

// 处理审核操作的通用方法
const handleDeal = async (item: TodoItem, agree: boolean) => {
  try {
    dealLoading.value = true;
    let result;

    // 根据type字段调用对应的审核接口
    switch (item.type) {
      case "1": // 合同
        result = await dealContractApi(item.id, agree, "");
        break;
      case "2": // 报销
        result = await dealBaoXiaoApi(item.id, agree, "");
        break;
      case "3": // 付款
        result = await dealPayApi(item.id, agree, "", item.payObject?.toString() || "");
        break;
      default:
        showToast("未知的待办类型");
        return;
    }

    if (result.code === 0) {
      const action = agree ? "同意" : "拒绝";
      showToast(`${action}成功：${item.name}`);

      // 无感知刷新待办事项列表 - 不显示loading状态
      await getOAStatistics(false);
    } else {
      showToast(result.msg || "操作失败");
    }
  } catch (error) {
    console.error("审核操作失败:", error);
    showToast("操作失败，请重试");
  } finally {
    dealLoading.value = false;
  }
};

// 处理拒绝
const handleReject = (item: TodoItem) => {
  handleDeal(item, false);
};

// 处理同意
const handleApprove = (item: TodoItem) => {
  handleDeal(item, true);
};

// 使用公共枚举的获取名称方法
const getContractTypeName = getAmountTypeName;



// 跳转到OA审批页面
const goToApprovals = (tabIndex?: number) => {
  const query: any = {};

  if (tabIndex !== undefined) {
    query.tab = tabIndex.toString();
  }

  // 不再传递统计数据，让approvals页面获取最新数据
  router.push({
    path: "/approvals",
    query,
  });
};

// 打开AI助手 - 直接跳转到DeepSeek网页
const openAI = () => {
  const deepseekUrl = "https://chat.deepseek.com/";
  
  try {
    // 检测是否为移动设备或安卓壳子环境
    const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
    
    if (isMobile) {
      // 移动设备直接跳转，避免弹窗被阻止
      window.location.href = deepseekUrl;
      showToast("正在打开DeepSeek AI助手...");
    } else {
      // 桌面端尝试新窗口打开
      const newWindow = window.open(deepseekUrl, "_blank");
      
      if (!newWindow) {
        // 如果被浏览器阻止弹窗，降级为直接跳转
        window.location.href = deepseekUrl;
        showToast("正在打开DeepSeek AI助手...");
      } else {
        showToast("正在打开DeepSeek AI助手...");
      }
    }
  } catch (error) {
    console.error("打开DeepSeek失败:", error);
    // 兜底方案：直接跳转
    try {
      window.location.href = deepseekUrl;
      showToast("正在打开DeepSeek AI助手...");
    } catch (fallbackError) {
      console.error("兜底跳转也失败:", fallbackError);
      showToast("打开失败，请手动访问 chat.deepseek.com");
    }
  }
};

// 页面挂载时初始化数据
onMounted(() => {
  // 优化加载体验：先尝试快速加载，如果超过200ms才显示loading
  let loadingTimer: NodeJS.Timeout | null = null
  let isDataLoaded = false
  
  // 延迟显示loading，避免闪烁
  loadingTimer = setTimeout(() => {
    if (!isDataLoaded) {
      // 如果200ms后数据还没加载完成，才显示loading状态
      loading.value = true
    }
  }, 200)
  
  // 立即开始数据加载
  requestAnimationFrame(async () => {
    try {
      // 先获取当前用户信息以判定是否显示公告模块
      await getCurrentUserInfo();
      await getOAStatistics()
      // 获取未读消息数量以切换消息图标
      await fetchUnreadStatus();
      isDataLoaded = true
      // 数据加载完成，清除loading定时器
      if (loadingTimer) {
        clearTimeout(loadingTimer)
        loadingTimer = null
      }
      loading.value = false
    } catch (error) {
      isDataLoaded = true
      // 即使出错也要清除定时器
      if (loadingTimer) {
        clearTimeout(loadingTimer)
        loadingTimer = null
      }
      loading.value = false
    }
  })
})

// 预加载优化：在路由进入前预加载数据
const preloadData = () => {
  // 静默获取数据，不显示loading
  getOAStatistics(false);
};

// 导出预加载函数供路由使用
defineExpose({
  preloadData
});
</script>

<style lang="scss" scoped>
@import url("./style/index.scss");
</style>